package com.wn.order.service.impl;

import com.wn.order.client.AccountClient;
import com.wn.order.client.StorageClient;
import com.wn.order.entity.Order;
import com.wn.order.mapper.OrderMapper;
import com.wn.order.service.OrderService;
import feign.FeignException;
//import io.seata.spring.annotation.GlobalTransactional;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private StorageClient storageClient;

    @Autowired
    private OrderMapper orderMapper;

    // 全局的注解
    @GlobalTransactional   //分布式事务
    @Override
    public Long create(Order order) {

        // !!!xid检查
        String xid = RootContext.getXID();

        log.info("请求参数:{}", order);

        // 创建订单
        orderMapper.insert(order);  //往 order-表里添加数据 (这个服务 创建订单 )
        try {

            //远程调用 账号服务   进行远程调用    (这个服务扣钱)
            // 扣减余额
            accountClient.deduct(order.getUserId(), order.getMoney());

            //远程调用 库存服务  进行远程调用     (这个服务扣库存)

            // 扣减库存
            storageClient.deduct(order.getGoodsNo(), order.getBuyCount());

        } catch (FeignException e) {
            log.error("下单失败，原因:{}", e.contentUTF8(), e);
            throw new RuntimeException(e.contentUTF8(), e);
        }
        return order.getId();
    }
}
